const Koa = require("koa");
const app = new Koa();
const mongoose = require("mongoose");
const json = require("koa-json");
const bodyParser = require("koa-bodyparser"); //用于解析请求体
const Router = require("@koa/router"); //用于路由处理
const router = new Router();
const cors = require("@koa/cors"); //用于处理跨域请求
const { addAliases } = require("module-alias");
const koaMorgan = require("koa-morgan");
const dotenv = require("dotenv");
dotenv.config();
// 配置别名
addAliases({
  "@": __dirname,
});

const responseHandler = require("@/utils/result");
const errorHandler = require("@/utils/abnormal");
// 统一返回给前端的接口数据格式：中间件
app.use(responseHandler);
app.use(errorHandler);

app.use(koaMorgan("dev"));
app.use(json());
app.use(bodyParser());
app.use(cors());
// 连接数据库
mongoose
  .connect(process.env.DB_HOST)
  .then((res) => {
    console.log("数据库连接成功");
  })
  .catch((err) => {
    console.error("数据库连接失败", err);
  });

// ----------小程序端接口-----------
// 登录注册用户账号
const login = require("@/router/user");
const article = require("@/router/article");
const home = require("@/router/home");
// 搜索游记
const searchTravel = require("@/router/search-travel");
// 目的地
const found = require("@/router/found");
// 结伴
const companion = require("@/router/companion");
// ----------PC端接口-----------
const pcAdmin = require("@/router/pc-admin");
const pcDataAnalysis = require("@/router/pc-data-analysis");

router.use("/apif", login);
router.use("/apif", article);
router.use("/apif", home);
router.use("/apif", pcAdmin);
router.use("/apif", searchTravel);
router.use("/apif", found);
router.use("/apif", companion);
router.use("/apif", pcDataAnalysis);
app.use(router.routes()).use(router.allowedMethods());

app.listen(process.env.PORT, () => {
  console.log(`服务器启动成功,端口号为${process.env.PORT}`);
});
